package org.qee.counter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class CounterService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void setCounter(String key, Long value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Long decr(String key) {
        RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        return redisTemplate.getConnectionFactory().getConnection().decr(keySerializer.serialize(key));
    }

    public Long decrBy(String key, Long value) {
        RedisSerializer<String> keySerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        return redisTemplate.getConnectionFactory().getConnection().decrBy(keySerializer.serialize(key), value);
    }

}
